package com.gg.cookice;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class cookice {

    /**
     * 增加cookice
     */
    public static void addCookice(HttpServletResponse response, String name, String value){
        Cookie cookie = new Cookie(name.trim(), value.trim());
        cookie.setMaxAge(60 * 60 * 30 * 60);// 设置为30min
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 查询cookice
     */
    public static Object selectCookice(HttpServletRequest request, Object name){
        Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
        if (null==cookies) {
            return null;
        } else {
            for(Cookie cookie : cookies){
                if(cookie.getName().equals(name)){
                    return cookie.getValue();
                }
            }
            return null;
        }
    }

    /**
     * 删除cookice
     */
    public static Object delectCookice(HttpServletRequest request,HttpServletResponse response,String name){
        Cookie[] cookies = request.getCookies();
        try {
            if (null==cookies) {
                return true;
            } else {
                for(Cookie cookie : cookies){
                    if(cookie.getName().equals(name)){
                        cookie.setValue(null);
                        cookie.setMaxAge(0);// 立即销毁cookie
                        cookie.setPath("/");
                        response.addCookie(cookie);
                        break;
                    }
                }
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
